package com.rxt.thermopro.ui.activity

import android.Manifest
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.app.common.base.BaseActivity
import com.rxt.thermopro.R
import com.rxt.thermopro.adapter.DeviceListAdapter
import com.rxt.thermopro.app.AppContext
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.EventAlarmData
import com.rxt.thermopro.bean.ProfileBean
import com.rxt.thermopro.ui.dialog.*
import com.rxt.thermopro.ui.fragment.DeviceListFragment
import com.rxt.thermopro.viewmodel.BleMessageViewModel
import com.rxt.thermopro.viewmodel.DeviceListViewModel
import com.rxt.thermopro.viewmodel.DeviceStatusViewModel
import kotlin.system.exitProcess


class DeviceListActivity : BaseActivity<DeviceListViewModel>() {

    override fun layoutId(): Int {
        return R.layout.activity_device_list
    }

    private lateinit var mDeviceStatusViewModel: DeviceStatusViewModel
    private lateinit var mBleViewModel: BleMessageViewModel

    private lateinit var manager: NotificationManager
    private val lastDisconnectAlarmTime = hashMapOf<String, Long>()
    private val mDialog = Temp100Dialog()
    private var probeStatusTP960P =  hashMapOf<String, Int>()
    private var probeDisconnectDialog: ProbeDisconnectDialog? = null
    private var disconnectDialogList = mutableListOf<DisconnectDialog>()

    override fun initView(savedInstanceState: Bundle?) {

        mDeviceStatusViewModel =
            ViewModelProvider(this).get(DeviceStatusViewModel::class.java)
        mBleViewModel =
            ViewModelProvider(this).get(BleMessageViewModel::class.java)
        supportFragmentManager.beginTransaction()
            .add(
                R.id.mainContent,
                DeviceListFragment.newInstance(1)
            )
            .addToBackStack("main")
            .commit()

        manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "alarm";
            val channelName = "alarm";
            val importance = NotificationManager.IMPORTANCE_HIGH
            createNotificationChannel(channelId, channelName, importance);
        }

        mDeviceStatusViewModel.alarmClock1.observeForever(Observer {
            if (it.values.last().isEmpty()) {
                mViewModel.alarmClockDialog1.postValue(hashMapOf<Long, String>().apply {
                    this[System.currentTimeMillis()] = it.keys.last()
                })
                val profileName = LocalDataDao.INSTANCE.getProfile1(it.keys.last()).name
                val alarmText = LocalDataDao.INSTANCE.getAlarmText1(it.keys.last())
                sendNotification(
                    "${resources.getString(R.string.text_probe)}1 $profileName ${
                        resources.getString(R.string.text_timer_ended)
                    }", alarmText, 1, R.drawable.time_alarm_icon_title
                )
            }
        })

        mViewModel.alarmClockDialog1.observeInActivity(this, Observer {
            if (it.values.last().isNotEmpty()) {
                val dialog = AlarmDialog().apply {
                    showDialog(supportFragmentManager)
                }
                dialog.setAlarmNum("1", it.values.last())
            }
        })

        mDeviceStatusViewModel.alarmClock2.observeForever(Observer {
            if (it.values.last().isEmpty()) {
                mViewModel.alarmClockDialog2.postValue(hashMapOf<Long, String>().apply {
                    this[System.currentTimeMillis()] = it.keys.last()
                })
                val profileName = LocalDataDao.INSTANCE.getProfile2(it.keys.last()).name
                val alarmText = LocalDataDao.INSTANCE.getAlarmText2(it.keys.last())
                sendNotification(
                    "${resources.getString(R.string.text_probe)}2 $profileName ${
                        resources.getString(R.string.text_timer_ended)
                    }", alarmText, 2, R.drawable.time_alarm_icon_title
                )
            }
        })

        mViewModel.alarmClockDialog2.observeInActivity(this, Observer {
            if (it.values.last().isNotEmpty()) {
                val dialog = AlarmDialog().apply {
                    showDialog(supportFragmentManager)
                }
                dialog.setAlarmNum("2", it.values.last())
            }
        })

        mDeviceStatusViewModel.alarmClock3.observeForever(Observer {
            if (it.values.last().isEmpty()) {
                mViewModel.alarmClockDialog3.postValue(hashMapOf<Long, String>().apply {
                    this[System.currentTimeMillis()] = it.keys.last()
                })
                val profileName = LocalDataDao.INSTANCE.getProfile3(it.keys.last()).name
                val alarmText = LocalDataDao.INSTANCE.getAlarmText3(it.keys.last())
                sendNotification(
                    "${resources.getString(R.string.text_probe)}3 $profileName ${
                        resources.getString(R.string.text_timer_ended)
                    }", alarmText, 3, R.drawable.time_alarm_icon_title
                )
            }
        })

        mViewModel.alarmClockDialog3.observeInActivity(this, Observer {
            if (it.values.last().isNotEmpty()) {
                val dialog = AlarmDialog().apply {
                    showDialog(supportFragmentManager)
                }
                dialog.setAlarmNum("3", it.values.last())
            }
        })

        mDeviceStatusViewModel.alarmClock4.observeForever(Observer {
            if (it.values.last().isEmpty()) {
                mViewModel.alarmClockDialog4.postValue(hashMapOf<Long, String>().apply {
                    this[System.currentTimeMillis()] = it.keys.last()
                })
                val profileName = LocalDataDao.INSTANCE.getProfile4(it.keys.last()).name
                val alarmText = LocalDataDao.INSTANCE.getAlarmText4(it.keys.last())
                sendNotification(
                    "${resources.getString(R.string.text_probe)}4 $profileName ${
                        resources.getString(R.string.text_timer_ended)
                    }", alarmText, 4, R.drawable.time_alarm_icon_title
                )
            }
        })

        mViewModel.alarmClockDialog4.observeInActivity(this, Observer {
            if (it.values.last().isNotEmpty()) {
                val dialog = AlarmDialog().apply {
                    showDialog(supportFragmentManager)
                }
                dialog.setAlarmNum("1", it.values.last())
            }
        })

        mBleViewModel.notifyTP960ProbeStatusForever.observeForever(Observer {
            if (it.isNotEmpty()) {
                it[it.keys.last()]?.let { item ->
                    if (item.second != 1) {
                        probeStatusTP960P[it.keys.last()] = 0
                        println("123-> ProbeStatus  probeIndex=0  status=0   notifyTP960ProbeStatusForever")
                        mViewModel.postDelay({
                            if (probeStatusTP960P[it.keys.last()] == 0) {
                                if (lastDisconnectAlarmTime.containsKey(it.keys.last())) {
                                    val lastTime = lastDisconnectAlarmTime[it.keys.last()] ?: 0L
                                    val status =
                                        lastDisconnectAlarmTime[it.keys.last() + "_status"] ?: 0L
                                    //test
//                                    val status =0L
                                    val now = System.currentTimeMillis()
                                    println("123-> ProbeStatus  probeIndex=0  status1=$status   notifyTP960ProbeStatusForever")
                                    if (now - lastTime > 5000 && status != 19L) {
                                        sendNotification(
                                            resources.getString(R.string.text_disconnection),
                                            resources.getString(R.string.text_probe_disconnect), 6,
                                            R.drawable.disconnect_alarm_icon_title
                                        )
                                        //探针断开报警
                                        if (LocalDataDao.INSTANCE.isAlarm(it.keys.last()) ||
                                            LocalDataDao.INSTANCE.isAlarmVibration(it.keys.last())) {
                                            AppContext.get().alarm(it.keys.last())
                                        }
                                    }
                                    val newIt = hashMapOf<String, Pair<Int, String>>().apply {
                                        this[it.keys.last()] =
                                            item.first to (item.second.toString() + "_" + status.toString())
                                    }
                                    mViewModel.notifyTP960ProbeStatus.postValue(newIt)
                                    lastDisconnectAlarmTime.clear()
                                } else {
                                    sendNotification(
                                        resources.getString(R.string.text_disconnection),
                                        resources.getString(R.string.text_probe_disconnect), 6,
                                        R.drawable.disconnect_alarm_icon_title
                                    )
                                    //探针断开报警
                                    if (LocalDataDao.INSTANCE.isAlarm(it.keys.last()) ||
                                        LocalDataDao.INSTANCE.isAlarmVibration(it.keys.last())) {
                                        AppContext.get().alarm(it.keys.last())
                                    }
                                    val newIt = hashMapOf<String, Pair<Int, String>>().apply {
                                        this[it.keys.last()] =
                                            item.first to (item.second.toString() + "_0")
                                    }
                                    mViewModel.notifyTP960ProbeStatus.postValue(newIt)
                                }
                            }
                        }, 6000)
                    } else {
                        probeStatusTP960P[it.keys.last()] = 1
                        lastDisconnectAlarmTime.clear()
                        println("123-> ProbeStatus  probeIndex=0  status=1   notifyTP960ProbeStatusForever")
                        AppContext.get().stopAlarm(it.keys.last())
                        val newIt = hashMapOf<String, Pair<Int, String>>().apply {
                            this[it.keys.last()] =
                                item.first to (item.second.toString() + "_1")
                        }
                        mViewModel.notifyTP960ProbeStatus.postValue(newIt)
                    }
                }
            }
        })

        mViewModel.notifyTP960ProbeStatus.observeInActivity(this, Observer {
            if (it.isNotEmpty()) {
                it[it.keys.last()]?.let { item ->
                    val probeStatus = item.second.split("_")[0].toInt() ?: 0
                    val status = item.second.split("_")[1].toInt() ?: 0
                    if (probeStatus != 1 && status != 19) {
                        probeDisconnectDialog = ProbeDisconnectDialog().apply {
                            setAddress(it.keys.last())
                            showDialog(supportFragmentManager)
                        }
                    } else if (probeStatus == 1) {
                        probeDisconnectDialog?.hideDialog()
                    }
                }
            }
        })


        //断开连接
        mBleViewModel.disconnectForeverData.observeForever(Observer {
            lastDisconnectAlarmTime[it.first] = it.second.split("_")[0].toLong()
            lastDisconnectAlarmTime[it.first + "_status"] = it.second.split("_")[1].toLong()
            val status = it.second.split("_")[1].toInt()
            if (status != 19) {
                AppContext.get().alarm(it.first)
                sendNotification(
                    resources.getString(R.string.text_disconnection),
                    resources.getString(R.string.text_disconnect_alarm), 5,
                    R.drawable.disconnect_alarm_icon_title
                )
            }
            mViewModel.disconnectData.postValue(it)
        })

        mViewModel.disconnectData.observeInActivity(this, Observer {
            val status = it.second.split("_")[1].toInt()
            if (status != 19) {
                val disconnectDialog = DisconnectDialog().apply {
                    showTextByAddress(it.first)
                    showDialog(supportFragmentManager)
                }
                disconnectDialogList.add(disconnectDialog)
            }
        })

        mBleViewModel.reConnectSuccess.observeInActivity(this, Observer {
            if (it.isNotEmpty()) {
                if (disconnectDialogList.isNotEmpty()){
                    val needRemove= mutableListOf<DisconnectDialog>()
                    disconnectDialogList.forEach { dialog ->
                        if (dialog.getAddress() == it.keys.last()) {
                            dialog.hideDialog()
                            needRemove.add(dialog)
                        }
                    }
                    disconnectDialogList.removeAll(needRemove)
                }
            }
        })

        //停止报警
        mBleViewModel.notifyTP960AlarmClose.observeForever(Observer {
            AppContext.get().stopAlarm(it.keys.last())
        })

        mBleViewModel.notifyRefreshTempData.observeForever(Observer {
            val deviceType = LocalDataDao.INSTANCE.getDeviceList().first { item ->
                item.address == it.last().address
            }.deviceType
            if (deviceType != DeviceListAdapter.VIEW_TYPE_TP359) {
                mBleViewModel.resetProfile(it)
                for (i in 0 until it.size) {
                    val tempNum = it[i].temperatureNUm
                    val profile = when (i) {
                        0 -> {
                            LocalDataDao.INSTANCE.getProfile1(it[i].address)
                        }
                        1 -> {
                            LocalDataDao.INSTANCE.getProfile2(it[i].address)
                        }
                        2 -> {
                            LocalDataDao.INSTANCE.getProfile3(it[i].address)
                        }
                        3 -> {
                            LocalDataDao.INSTANCE.getProfile4(it[i].address)
                        }
                        else -> {
                            ProfileBean(
                                "MEAT",
                                "", mutableListOf(), singleTemp = false
                            )
                        }
                    }
                    val list = LocalDataDao.INSTANCE.getTempPreAlarmList()
                    val currentPreTemp =
                        list[LocalDataDao.INSTANCE.getTempPreAlarm(it[i].address)].preTime.toInt()
                    val needAlarm = LocalDataDao.INSTANCE.isAlarm(it[i].address) ||
                            LocalDataDao.INSTANCE.isAlarmVibration(it[i].address)
                    if (tempNum.toIntOrNull() ?: -1 != -1 && needAlarm) {
                        alarmTemp(tempNum.toInt(), profile, i + 1, currentPreTemp, it[i].address)
                    }
                }
            } else {
                val tempNum = it.last().temperatureNUm
                val humNum = it.last().humidityNum
                val address = it.last().address
                val tempProfile = LocalDataDao.INSTANCE.getTempProfile359(address)
                val humProfile = LocalDataDao.INSTANCE.getHumProfile359(address)
                val needAlarm = LocalDataDao.INSTANCE.isTempAlarm359(address)
                val needAlarm1 = LocalDataDao.INSTANCE.isHumAlarm359(address)
//                countTest++
//                println("======>  countTest=$countTest   needAlarm=$needAlarm  needAlarm1=$needAlarm1")
                if (tempNum.toFloatOrNull() ?: -1 != -1 && needAlarm) {
//                    if (countTest==4){
//                        alarmTemp(36, tempProfile, 100, 0, address)
//                    }
                    //TP359 温度
                    alarmTemp(tempNum.toFloat().toInt(), tempProfile, 100, 0, address)
                }
                if (humNum.toIntOrNull() ?: -1 != -1 && needAlarm1) {
//                    if (countTest==7){
//                        alarmTemp(77, humProfile, 101, 0, address)
//                    }
                    //TP359 湿度
                    alarmTemp(humNum.toInt(), humProfile, 101, 0, address)
                }
            }
        })

        mViewModel.showAlarmDialog.observeInActivity(this, Observer {
            val dialog = TempAlarmDialog().apply {
                showDialog(supportFragmentManager)
            }
            val alarmData = it.values.last()
            dialog.setAlarmNum(
                alarmData.probeIndex, alarmData.tempNum,
                alarmData.deviceAddress
            )
            dialog.setOnStopListener(object : TempAlarmDialog.OnStopListener {
                override fun onStop() {
                    //不设置提前温度报警才发停止报警消息
                    if (alarmData.currentPreTemp.toInt() == 0) {
                        LocalDataDao.INSTANCE.setNeedResetProfile(
                            alarmData.probeIndex.toInt() - 1, alarmData.profileBean,
                            alarmData.deviceAddress
                        )
                        mBleViewModel.sendStopAlarmMsg(
                            alarmData.deviceAddress,
                            alarmData.probeIndex.toInt()
                        )
                    }
                }
            })
        })


//        mDeviceStatusViewModel.removeDevice.observeInActivity(this, Observer {
//            if (it.values.isNotEmpty()) {
//                supportFragmentManager.fragments.forEach { item ->
//                    if (item is DeviceSettingFragment || item is DataChartsFragment) {
//                        supportFragmentManager.beginTransaction().remove(item)
//                    }
//                }
//            }
//        })
        //温度超过100 报警 暂停使用
        mViewModel.startCheckTemp({
            println("123->  startCheckTemp block  temp>100")
            if (it) {
                mDialog.showDialog(supportFragmentManager)
            } else {
                mDialog.hideDialog()
            }
        }, {
            mBleViewModel.cacheMsgData
        })

        //后台Service重连
        mBleViewModel.reConnectService.observeInActivity(this, Observer {
            AppContext.get().connectService()
            mViewModel.postDelay({
                AppContext.get().startCheckConnectWorking(this)
            }, 3000)
        })

    }

    var countTest = 1

    private fun alarmTemp(
        tempNum: Int,
        profileBean: ProfileBean,
        probeIndex: Int,
        currentPreTemp: Int,
        deviceAddress: String
    ) {
        if (profileBean.highTemperatureNum.isNotEmpty() && profileBean.lowTemperatureNum.isNotEmpty()
            && !profileBean.singleTemp
        ) {
            if (checkTempAlarm(tempNum, profileBean, currentPreTemp, true)
            ) {
                if (!LocalDataDao.INSTANCE.hasAlarmProfile(
                        probeIndex,
                        profileBean,
                        currentPreTemp,
                        deviceAddress
                    )
                ) {
                    if (probeIndex > 99) {
                        AppContext.get().alarm(0, deviceAddress)
                    } else {
                        AppContext.get().alarm(probeIndex - 1, deviceAddress)
                    }
                    //警报弹窗  (温度)
                    mViewModel.showAlarmDialog.postValue(hashMapOf<Long, EventAlarmData>().apply {
                        this[System.currentTimeMillis()] = EventAlarmData(
                            probeIndex.toString(), tempNum.toString(),
                            deviceAddress, currentPreTemp.toString(), profileBean
                        )
                    })

                    LocalDataDao.INSTANCE.setHasAlarmProfile(
                        probeIndex,
                        profileBean,
                        currentPreTemp,
                        deviceAddress
                    )

                    sendNotification(
                        "${resources.getString(R.string.text_probe)} $probeIndex " +
                                profileBean.name +
                                " ${LocalDataDao.INSTANCE.convertUnit(tempNum.toString())}",
                        resources.getString(R.string.text_temp_higher_than), 7,
                        R.drawable.warn_temp
                    )
                }
            } else {
                if (LocalDataDao.INSTANCE.hasAlarmProfile(
                        probeIndex,
                        profileBean,
                        currentPreTemp,
                        deviceAddress
                    )
                ) {
                    LocalDataDao.INSTANCE.removeAlarmProfile(probeIndex, deviceAddress)
                }
            }
            //停止时间预测
//            if (tempNum >= profileBean.highTemperatureNum.toInt()) {
//                if (mDeviceStatusViewModel.isBlockTimeWorking(probeIndex - 1, deviceAddress)) {
//                    mDeviceStatusViewModel.resetBlockTimeWorking(probeIndex - 1, deviceAddress)
//                }
//            }
        } else if (profileBean.singleTemp) {
            if (checkTempAlarm(tempNum, profileBean, currentPreTemp, false)) {
                if (!LocalDataDao.INSTANCE.hasAlarmProfile(
                        probeIndex,
                        profileBean,
                        currentPreTemp,
                        deviceAddress
                    )
                ) {
                    if (probeIndex > 99) {
                        AppContext.get().alarm(0, deviceAddress)
                    } else {
                        AppContext.get().alarm(probeIndex - 1, deviceAddress)
                    }
                    AppContext.get().alarm(probeIndex - 1, deviceAddress)
                    //警报弹窗  (温度)
                    mViewModel.showAlarmDialog.postValue(hashMapOf<Long, EventAlarmData>().apply {
                        this[System.currentTimeMillis()] = EventAlarmData(
                            probeIndex.toString(), tempNum.toString(),
                            deviceAddress, currentPreTemp.toString(), profileBean
                        )
                    })

                    LocalDataDao.INSTANCE.setHasAlarmProfile(
                        probeIndex,
                        profileBean,
                        currentPreTemp,
                        deviceAddress
                    )
                    sendNotification(
                        "${resources.getString(R.string.text_probe)} $probeIndex " +
                                profileBean.name +
                                " ${LocalDataDao.INSTANCE.convertUnit(tempNum.toString())}",
                        resources.getString(R.string.text_temp_higher_than), 7,
                        R.drawable.warn_temp
                    )
                }
            } else {
                if (LocalDataDao.INSTANCE.hasAlarmProfile(
                        probeIndex,
                        profileBean,
                        currentPreTemp,
                        deviceAddress
                    )
                ) {
                    LocalDataDao.INSTANCE.removeAlarmProfile(probeIndex, deviceAddress)
                }
            }

            //停止时间预测
//            if (tempNum >= profileBean.highTemperatureNum.toInt()) {
//                mDeviceStatusViewModel.resetBlockTimeWorking(probeIndex - 1, deviceAddress)
//            }
        }
    }

    /**
     * 检测温度是否到达目标温度
     */
    private fun checkTempAlarm(
        tempNum: Int,
        profileBean: ProfileBean,
        currentPreTemp: Int,
        isRange: Boolean
    ): Boolean {
        return if (isRange) {
            if (LocalDataDao.INSTANCE.getTempUnit() == LocalDataDao.TEMP_UNIT_C) {
                tempNum >= profileBean.highTemperatureNum.toInt() - currentPreTemp || tempNum <=
                        profileBean.lowTemperatureNum.toInt() - currentPreTemp
            } else {
                val newTempNum =
                    LocalDataDao.INSTANCE.transUnitCToF(tempNum.toString()).toInt()
                val newProfileHighNum = LocalDataDao.INSTANCE.transUnitCToF(
                    profileBean.highTemperatureNum
                ).toInt()
                val newProfileLowNum = LocalDataDao.INSTANCE.transUnitCToF(
                    profileBean.lowTemperatureNum
                ).toInt()
                newTempNum >= newProfileHighNum - currentPreTemp || newTempNum <=
                        newProfileLowNum - currentPreTemp
            }
        } else {
            if (LocalDataDao.INSTANCE.getTempUnit() == LocalDataDao.TEMP_UNIT_C) {
                tempNum >= profileBean.highTemperatureNum.toInt() - currentPreTemp
            } else {
                val newTempNum =
                    LocalDataDao.INSTANCE.transUnitCToF(tempNum.toString()).toInt()
                val newProfileHighNum = LocalDataDao.INSTANCE.transUnitCToF(
                    profileBean.highTemperatureNum
                ).toInt()
                newTempNum >= newProfileHighNum - currentPreTemp
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    fun createNotificationChannel(channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance);
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }


    private fun sendNotification(nTitle: String, nContent: String, id: Int, nIcon: Int) {
        val resultIntent = Intent(applicationContext, DeviceListActivity::class.java)
        resultIntent.putExtra("content", nContent)
        resultIntent.putExtra("id", id)
        resultIntent.putExtra("title", nTitle)
        val pendingIntent =
            PendingIntent.getActivity(
                application, 123,
                resultIntent, PendingIntent.FLAG_CANCEL_CURRENT
            )

        val notification = NotificationCompat.Builder(this, "alarm")
            .setAutoCancel(true)
            .setContentTitle(nTitle)
            .setContentText(nContent)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(nIcon)
            //设置红色
            .setColor(Color.parseColor("#F00606"))
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
            .setContentIntent(pendingIntent)
            .build();
        manager.notify(id, notification);
    }

    override fun onBackPressed() {
        if (supportFragmentManager.backStackEntryCount > 1) {
            supportFragmentManager.popBackStack()
        } else {
            AlertDialog.Builder(this)
                .setTitle(R.string.text_exit_alert)
                .setMessage(R.string.text_exit_message)
                .setNegativeButton(R.string.text_Cancel) { _, _ ->

                }
                .setPositiveButton(R.string.text_ok) { _, _ ->
                    finish()
                    android.os.Process.killProcess(android.os.Process.myPid())
                    exitProcess(0)
                }
                .show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
//            AlertDialog.Builder(this@DeviceListActivity)
//                .setMessage(R.string.text_need_location_permission)

            val dialog = AlertDialog.Builder(this@DeviceListActivity)
                .setMessage(R.string.text_need_location_permission)
                .setPositiveButton(R.string.text_yes) { _, _ ->
                    goToSystemPermissionUi()
                }
                .show()
            dialog.getButton(DialogInterface.BUTTON_POSITIVE)
                .setTextColor(resources.getColor(R.color.gray_text))
            dialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                .setTextColor(resources.getColor(R.color.gray_text))
        }
    }

    private fun goToSystemPermissionUi() {
        val intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
        intent.data = Uri.fromParts("package", packageName, null)
        startActivity(intent)
    }

    private fun checkPermissions() {
        val permissionArray = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        } else {
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }

//        val permissionArray = arrayOf(
//            Manifest.permission.ACCESS_FINE_LOCATION
//        )
        val requestPermissions = permissionArray.filter {
            ContextCompat.checkSelfPermission(
                this,
                it
            ) !== PackageManager.PERMISSION_GRANTED
        }
        if (requestPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                requestPermissions.toTypedArray(),
                6
            )
        }
    }

    override fun onStart() {
        super.onStart()
        checkPermissions()
    }

    override fun onDestroy() {
        AppContext.get().disConnectService()
        AppContext.get().stopAlarm()
        super.onDestroy()
    }


    override fun getResources(): Resources {
        val resources = super.getResources()
        if (resources != null) {
            val configuration = resources.configuration
            val fontScale = configuration.fontScale
            val densityDpi = configuration.densityDpi
            println("===fontScale=$fontScale  densityDpi=$densityDpi")
            val newFont = if (fontScale > 1.25F) {
                (fontScale - 1.25F) / 2 + 1.25F
            } else {
                fontScale
            }
            configuration.fontScale = newFont   //0.85:小号  1:标准  1.25:大号  1.4:巨无霸
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                if (resources.displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
                    configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE // 恢复显示大小
                }
            }
//            resources.updateConfiguration(configuration, resources.displayMetrics)
//            createConfigurationContext(configuration)
        }
        return resources!!
    }
}